using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace CPlatePrintSys.Win.Controls
{
    public partial class BaseInfoTreeCtrl : UserControl
    {
        public static readonly DependencyProperty NodesProperty = DependencyProperty.Register(
            nameof(Nodes), typeof(ObservableCollection<BaseInfoTreeNode>), typeof(BaseInfoTreeCtrl), new PropertyMetadata(null));

        public ObservableCollection<BaseInfoTreeNode> Nodes
        {
            get => (ObservableCollection<BaseInfoTreeNode>)GetValue(NodesProperty);
            set => SetValue(NodesProperty, value);
        }

        public static readonly RoutedEvent NodeSelectedEvent = EventManager.RegisterRoutedEvent(
            nameof(NodeSelected), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(BaseInfoTreeCtrl));

        public event RoutedEventHandler NodeSelected
        {
            add { AddHandler(NodeSelectedEvent, value); }
            remove { RemoveHandler(NodeSelectedEvent, value); }
        }

        public BaseInfoTreeCtrl()
        {
            InitializeComponent();
            
            // 为TreeView添加选择改变事件
            var treeView = this.FindName("treeView") as TreeView;
            if (treeView != null)
            {
                treeView.SelectedItemChanged += TreeView_SelectedItemChanged;
            }
        }

        private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is BaseInfoTreeNode selectedNode)
            {
                // 触发自定义事件
                var args = new RoutedEventArgs(NodeSelectedEvent, selectedNode);
                RaiseEvent(args);
            }
        }

        public void LoadTestData()
        {
            //TODO 测试使用
            var root1 = new BaseInfoTreeNode("N11519");
            var a101a = new BaseInfoTreeNode("A101A", root1);
            root1.Children.Add(a101a);
            a101a.Children.Add(new BaseInfoTreeNode("7PA001", a101a));
            a101a.Children.Add(new BaseInfoTreeNode("7PA002", a101a));
            a101a.Children.Add(new BaseInfoTreeNode("7PA003", a101a));
            a101a.Children.Add(new BaseInfoTreeNode("7PA004", a101a));
            var root2 = new BaseInfoTreeNode("N11520");
            var root3 = new BaseInfoTreeNode("N11521");
            Nodes = new ObservableCollection<BaseInfoTreeNode>(new List<BaseInfoTreeNode> { root1, root2, root3 });
            this.DataContext = this;
        }
    }
} 